<template>
  <view class="section">
    <template v-if="!testFlag">
      <view class="container">
        <view class="top">
          <view class="time">
            <text>计时：{{ minuteNumber }}分{{ secondNumber }}秒</text>
          </view>
          <view class="title">
            <view class="title_content">
              <text class="title_text">{{ bookName }}/{{ chapterName }}</text>
              <text class="title_tips" v-if="type === 1"
                >点击音频播放英文,然后按正确顺序点击英文使排序正确</text
              >
              <text class="title_tips" v-if="type === 2"
                >看下面中文按正确顺序点击英文使排序正确</text
              >
            </view>
          </view>
        </view>
        <view class="tips" @click="play()" v-if="type === 1">
          <image
            src="https://hengxiao-resource.oss-cn-hangzhou.aliyuncs.com/web/resources/images/app/horn2.png"
            mode="widthFix"
          ></image>
        </view>
        <view class="tips" @click="play()" v-if="type === 2">
          <image
            src="https://hengxiao-resource.oss-cn-hangzhou.aliyuncs.com/web/resources/images/app/horn2.png"
            mode="widthFix"
          ></image>
          <text>{{ sentence.chinese }}</text>
        </view>
        <view class="content">
          <view class="box">
            <view>
              <view class="selected">
                <view
                  class="selected_content"
                  v-for="(answer, index) in sentence.answerList"
                  :key="index"
                  :class="{
                    active:
                      answer.index === index ||
                      (isSubmit && !sentence.selectList[index].isError),
                    error: isSubmit && sentence.selectList[index].isError,
                  }"
                >
                  <input
                    class="selected_button"
                    type="input"
                    v-model.trim="answer.word"
                    :disabled="answer.index === index || isSubmit"
                  />
                </view>
              </view>
              <!-- <view class="word">
                <view
                  class="word_content"
                  v-for="(word, index) in sentence.randomWordList"
                  :key="index"
                  :class="{ select: sentence.selectList[index].selected }"
                >
                  <view class="word_button" @click="selectWord(word, index)">
                    {{ word }}
                  </view>
                </view>
              </view> -->
            </view>
            <template v-if="sentence.isCorrect === true">
              <view class="result">
                <view class="result_top">
                  <image
                    src="https://hengxiao-resource.oss-cn-hangzhou.aliyuncs.com/web/resources/images/app/correct.png"
                  ></image>
                  <text class="correct">答对了,正确答案：</text>
                </view>
                <view class="result_bottom">
                  {{ sentence.sentence }}
                </view>
              </view>
            </template>
            <template v-if="sentence.isCorrect === false">
              <view class="result">
                <view class="result_top">
                  <image
                    src="https://hengxiao-resource.oss-cn-hangzhou.aliyuncs.com/web/resources/images/app/error.png"
                  ></image>
                  <text class="error">答错了,正确答案：</text>
                </view>
                <view class="result_bottom">
                  {{ sentence.sentence }}
                </view>
              </view>
            </template>
          </view>
          <view class="chart">
            <qiun-data-charts
              type="ring"
              :opts="opts"
              :chartData="chartData"
              background="none"
            />
          </view>
        </view>
        <view class="fixed">
          <view class="info">
            <view class="progress">
              <text>{{ currentSentenceNumber }}</text>
              <text>/{{ allSentenceNumber }}题</text>
            </view>
          </view>
          <view class="button">
            <view
              class="button_content next"
              :class="{
                disabled: sentence.isCorrect === false,
              }"
              @click="nextQuestion()"
            >
              <text>下一题</text>
            </view>
            <view
              class="button_content submit"
              :class="{
                disabled:
                  sentence.isCorrect === true || sentence.isCorrect === false,
              }"
              @click="submit()"
            >
              <text>提交</text>
            </view>
            <view
              class="button_content reselection"
              :class="{
                disabled: sentence.isCorrect === true,
              }"
              @click="reselection()"
            >
              <text>重写</text>
            </view>
          </view>
        </view>
      </view>
    </template>
    <u-mask :show="testFlag" :zoom="false">
      <view class="popup_container">
        <view class="popup_text">
          <text>训练完成,接下来进行学后测评。</text>
        </view>
        <view class="popup_button" @click="startEvaluation()">
          <text>开始评测</text>
        </view>
      </view>
    </u-mask>
    <Tips :show="showTips" :content="tipsContent"></Tips>
  </view>
</template>

<script>
const englishAudioContext = uni.createInnerAudioContext();
englishAudioContext.autoplay = true;
export default {
  components: {},
  filters: {
    typeFilter(type) {
      return type === 1 ? "句子听选" : "句子拼写";
    },
  },
  props: {
    type: {
      type: Number,
      default: 1,
    },
    sentence: {
      type: Object,
      default: null,
    },
    bookInfo: {
      type: Object,
      default: null,
    },
    chapterInfo: {
      type: Object,
      default: null,
    },
    sentenceSort: {
      type: Number,
      default: 0,
    },
    sentenceNum: {
      type: Number,
      default: 0,
    },
    testFlag: {
      type: Boolean,
      default: false,
    },
  },
  computed: {
    currentWidth() {
      return parseInt(
        (this.currentSentenceNumber / this.allSentenceNumber) * 100
      );
    },
  },
  created() {
    this.init();
  },
  mounted() {
    this.time();
  },
  data() {
    return {
      bookName: "",
      chapterName: "",
      currentSentenceNumber: 1,
      allSentenceNumber: 1,
      answerList: [],
      correctNumber: 0,
      errorNumber: 0,
      minute: 0,
      minuteNumber: "00",
      second: 0,
      secondNumber: "00",
      chartData: {},
      opts: {
        color: ["#0678b8", "#e4e3e8"],
        title: {
          name: "",
        },
        subtitle: {
          name: "",
        },
        extra: {
          ring: {
            centerColor: "#f3f3f3",
          },
        },
      },
      showTips: false,
      tipsContent: "请提交答案！",
      isSubmit: false,
    };
  },
  methods: {
    init() {
      if (this.testFlag) return;
      this.bookName = this.bookInfo.bookEdition + this.bookInfo.bookYear;
      this.chapterName = this.bookInfo.shortName;
      this.correctNumber = this.chapterInfo.correctCount;
      this.errorNumber = this.chapterInfo.wrongCount;
      this.currentSentenceNumber = this.sentenceSort + 1;
      this.allSentenceNumber = this.sentenceNum;
      this.initOptions();
      this.initEcharts();
      this.play();
    },
    initOptions() {
      let randomWords = this.sentence.randomWords;
      let answerList = [];
      let selectList = [];
      let reg = /\p{P}/u;
      for (let i = 0; i < randomWords.length; i++) {
        if (reg.test(randomWords[i])) {
          answerList.push({ word: randomWords[i], index: i });
          selectList.push({ selected: true });
        } else {
          answerList.push({ word: "", index: -1 });
          selectList.push({ selected: false });
        }
      }
      this.$set(this.sentence, "answerList", answerList);
      this.$set(this.sentence, "selectList", selectList);
      this.$set(this.sentence, "randomWordList", randomWords);
    },
    selectWord(word, i) {
      if (this.sentence.isCorrect === true || this.sentence.isCorrect === false)
        return;
      let isSelected = this.sentence.selectList[i].selected;
      if (isSelected) return;
      let answerList = this.sentence.answerList;
      answerList.some((item, index) => {
        if (item.word === "") {
          answerList.splice(index, 1, { word: word, index: i });
          return true;
        }
      });
      this.sentence.selectList[i].selected = true;
    },
    checkWord(answer, i) {
      if (this.sentence.isCorrect === true || this.sentence.isCorrect === false)
        return;
      if (answer.word === "") return;
      this.sentence.answerList[i].word = "";
      this.sentence.selectList[answer.index].selected = false;
    },
    checkRightAndWrong() {
      let answerList = this.sentence.answerList;
      let sentenceWords = this.sentence.sentenceWords;
      return answerList.some((item, index) => {
        if (item.word !== sentenceWords[index]) {
          return true;
        }
      });
    },
    nextQuestion() {
      if (this.sentence.isCorrect === false) return;
      if (this.sentence.isCorrect === undefined) {
        this.showTips = true;
        setTimeout(() => {
          this.showTips = false;
        }, 2000);
        return;
      }
      this.isSubmit = false;
      this.$emit("change");
    },
    submit() {
      this.isSubmit = true;
      if (this.sentence.isCorrect === true || this.sentence.isCorrect === false)
        return;
      if (!this.checkRightAndWrong()) {
        this.$set(this.sentence, "isCorrect", true);
        this.correctNumber += 1;
      } else {
        this.$set(this.sentence, "isCorrect", false);
        this.errorNumber += 1;
        for (let i = 0; i < this.sentence.answerList.length; i++) {
          if (
            this.sentence.answerList[i].word !== this.sentence.sentenceWords[i]
          ) {
            this.$set(this.sentence.selectList[i], "isError", true);
          } else {
            this.$set(this.sentence.selectList[i], "isError", false);
          }
        }
      }
      this.initEcharts();
      this.saveListeningRec();
    },
    reselection() {
      this.isSubmit = false;
      if (this.sentence.isCorrect === true) return;
      let isCorrect = this.sentence.isCorrect;
      if (isCorrect !== undefined) {
        this.$set(this.sentence, "isCorrect", undefined);
      }
      this.initOptions();
    },
    play() {
      if (!englishAudioContext.paused) return;
      englishAudioContext.src = this.sentence.audio;
      englishAudioContext.play();
    },
    time() {
      setInterval(() => {
        this.second++;
        if (this.second > 59) {
          this.second = 0;
          this.minute++;
        }
        if (this.second < 10) {
          this.secondNumber = this.second.toString().padStart(2, "0");
        } else {
          this.secondNumber = this.second.toString();
        }
        if (this.minute < 10) {
          this.minuteNumber = this.minute.toString().padStart(2, "0");
        } else {
          this.minuteNumber = this.minute.toString();
        }
      }, 1000);
    },
    initEcharts() {
      this.chartData = {
        series: [
          {
            data: [
              {
                name: "正确次数",
                value: this.correctNumber,
              },
              {
                name: "错误次数",
                value: this.errorNumber,
              },
            ],
          },
        ],
      };
    },
    saveListeningRec() {
      this.$emit("save", this.sentence.isCorrect);
    },
    startEvaluation() {
      this.$emit("view");
    },
  },
};
</script>

<style lang="scss" scoped>
@import "./SentencePractice2.scss";
</style>
